import Bullet from './bullet';

const BIANBIAN_IMG_PREFIX = 'images/bianbian';
const BIANBIAN_FRAME_COUNT = 1;
const BIANBIAN_WIDTH = 50;
const BIANBIAN_HEIGHT = 50;

export default class BianbianBullet extends Bullet {
  constructor() {
    super();
    this.imgPrefix = BIANBIAN_IMG_PREFIX;
    this.frameCount = BIANBIAN_FRAME_COUNT;
    this.width = BIANBIAN_WIDTH;
    this.height = BIANBIAN_HEIGHT;
    this.damage = 20; // 基础伤害
    this.range = 300; // 范围伤害半径
    this.effectDuration = 60; // 效果持续时间（60帧 = 1秒）
    this.updateImage(); // 更新图片
  }

  init(x, y, speed, damage=20) {
    super.init(x, y, speed, damage);
  }

  // 重写碰撞检测方法，实现范围伤害和方向改变效果
  checkCollisionWithZombies() {
    const zombies = GameGlobal.zombieManager ? GameGlobal.zombieManager.zombies : [];
    
    // 先检测是否与任何僵尸直接碰撞
    for (let i = zombies.length - 1; i >= 0; i--) {
      const zombie = zombies[i];
      
      if (zombie.isDead) continue;
      
      if (this.isCollideWith(zombie)) {
        this.triggerAreaEffect();
        this.destroy();
        break;
      }
    }  
  }

  // 触发范围效果
  triggerAreaEffect() {
    const zombies = GameGlobal.zombieManager ? GameGlobal.zombieManager.zombies : [];
    
    // 遍历所有僵尸，检查是否在范围内
    for (let i = zombies.length - 1; i >= 0; i--) {
      const zombie = zombies[i];
      
      if (zombie.isDead) continue;
      
      // 计算僵尸与子弹的距离
      const dx = zombie.x - this.x;
      const dy = zombie.y - this.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      // 如果在范围内
      if (distance <= this.range) {
        // 造成伤害
        zombie.takeDamage(this.damage);
        // 改变僵尸移动方向
        this.reverseZombieDirection(zombie);
      }
    }
  }

  // 改变僵尸移动方向为与子弹相反的方向
  reverseZombieDirection(zombie) {
    // 计算僵尸到子弹的向量
    const dx =  zombie.x-this.x;
    const dy = zombie.y-this.y;
    
    // 计算向量长度（距离）
    const distance = Math.sqrt(dx * dx + dy * dy);
    
    // 计算单位向量（确保距离不为0）
    let unitX = 0;
    let unitY = 0;
    if (distance > 0) {
      unitX = dx / distance*2;
      unitY = dy / distance/2;
    }
    
    // 设置僵尸临时方向为单位向量方向，持续effectDuration帧
    zombie.setTemporaryDirection(unitX, unitY, this.effectDuration);
  }

   remove() {
    this.isActive = false;
    this.visible = false;
    // 回收子弹对象
    GameGlobal.databus.removeBullets(this,"bianbianBullet");
  }
}